<template>
  <div class="map-container">
    <div id="map-container" ref="mapContainer"></div>
    <div class="control-panel">
      <button @click="createPolygon" :disabled="!isMapReady || isEditing">新建</button>
      <button @click="startEditing" :disabled="!isMapReady || !activePolygon || isEditing">开始编辑</button>
      <button @click="stopEditing" :disabled="!isMapReady || !isEditing">结束编辑</button>
      <button @click="deleteActivePolygon" :disabled="!isMapReady || !activePolygon">删除当前</button>
      <button @click="saveCurrentPolygon" :disabled="!isMapReady || !activePolygon">保存当前</button>
      <button @click="saveAllPolygons" :disabled="!isMapReady || polygons.length === 0">保存全部</button>
      <div class="status-info" v-if="activePolygon">
        当前{{ isEditing ? '正在编辑' : '选中' }}: {{ activePolygon.getExtData().name || '未命名多边形' }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import type { AMap, Map, Polygon, PolygonEditor, MapPolygon } from '@/types/amap';

defineOptions({
  name: 'AMapPolygonEditor',
  inheritAttrs: false
});

interface Props {
  apiKey: string;
  initialCenter?: [number, number];
  initialZoom?: number;
  initialPolygons?: MapPolygon[];
}

const props = withDefaults(defineProps<Props>(), {
  apiKey: '',
  initialCenter: () => [116.471354, 39.994257],
  initialZoom: 16,
  initialPolygons: () => []
});

const emit = defineEmits<{
  (e: 'map-loaded', map: Map): void;
  (e: 'polygon-created', polygon: Polygon): void;
  (e: 'polygon-updated', polygon: Polygon): void;
  (e: 'polygon-deleted', polygonId: string): void;
  (e: 'save-current', data: any): void;
  (e: 'save-all', data: any): void;
  (e: 'error', error: Error): void;
}>();

const mapContainer = ref<HTMLElement | null>(null);
const mapInstance = ref<Map | null>(null);
const polygons = ref<Polygon[]>([]);
const polygonEditor = ref<PolygonEditor | null>(null);
const activePolygon = ref<Polygon | null>(null);
const isMapReady = ref(false);
const isLoading = ref(false);
const error = ref<Error | null>(null);
const isEditing = ref(false);

const initMap = async () => {
  if (!props.apiKey) {
    error.value = new Error('AMap API key is required');
    emit('error', error.value);
    return;
  }

  isLoading.value = true;

  try {
    await AMapLoader.load({
      key: props.apiKey,
      version: '2.0',
      plugins: ['AMap.PolygonEditor'],
    });

    if (!window.AMap) throw new Error('AMap API加载失败');
    const AMap = window.AMap as AMap;

    mapInstance.value = new AMap.Map('map-container', {
      viewMode: '2D',
      center: props.initialCenter,
      zoom: props.initialZoom,
    });

    polygonEditor.value = new AMap.PolygonEditor(mapInstance.value);

    if (props.initialPolygons.length > 0) {
      await addInitialPolygons(AMap, props.initialPolygons);
    } else {
      await addDefaultPolygons(AMap);
    }

    setupEditorEvents();
    isMapReady.value = true;
    emit('map-loaded', mapInstance.value);
  } catch (err) {
    error.value = err instanceof Error ? err : new Error(String(err));
    emit('error', error.value);
  } finally {
    isLoading.value = false;
  }
};

const addInitialPolygons = async (AMap: AMap, initialPolygons: MapPolygon[] = []) => {
  if (!mapInstance.value) return;

  const newPolygons = initialPolygons.map(polyData => {
    // 默认样式
    const defaultStyle = {
      strokeColor: '#FF33FF',
      strokeWeight: 4,
      fillColor: '#1791fc',
      fillOpacity: 0.4
    };

    // 安全合并样式
    const finalStyle = polyData.style ?
      { ...defaultStyle, ...polyData.style } :
      defaultStyle;

    // 创建多边形
    const polygon = new AMap.Polygon({
      path: polyData.path.map(p => new AMap.LngLat(p[0], p[1])),
      ...finalStyle,
      extData: {
        id: polyData.id || `poly-${Date.now()}`,
        name: polyData.name || '未命名区域'
      }
    });

    // 添加双击事件
    polygon.on('dblclick', () => {
      setActivePolygon(polygon);
      startEditing();
    });

    return polygon;
  });

  // 添加到地图
  mapInstance.value.add(newPolygons);
  mapInstance.value.setFitView(newPolygons);
  polygons.value = newPolygons;

  // 设置吸附多边形
  if (polygonEditor.value && newPolygons.length > 0) {
    polygonEditor.value.addAdsorbPolygons(newPolygons);
    setActivePolygon(newPolygons[0]);
  }
};

const addDefaultPolygons = async (AMap: AMap) => {
  const path1: [number, number][] = [
    [116.475334, 39.997534],
    [116.476627, 39.998315],
    [116.478603, 39.99879],
    [116.478529, 40.000296],
    [116.475082, 40.000151],
    [116.473421, 39.998717],
  ];

  const path2: [number, number][] = [
    [116.474595, 40.001321],
    [116.473526, 39.999865],
    [116.476284, 40.000917],
  ];

  const polygon1 = new AMap.Polygon({
    path: path1,
    strokeColor: '#FF33FF',
    strokeWeight: 4,
    fillColor: '#1791fc',
    fillOpacity: 0.4,
    extData: { id: 'polygon1', name: '多边形1' },
  });

  const polygon2 = new AMap.Polygon({
    path: path2,
    strokeColor: '#FF33FF',
    strokeWeight: 4,
    fillColor: '#1791fc',
    fillOpacity: 0.4,
    extData: { id: 'polygon2', name: '多边形2' },
  });

  if (mapInstance.value) {
    mapInstance.value.add([polygon1, polygon2]);
    mapInstance.value.setFitView([polygon1, polygon2]);
  }

  polygon1.on('dblclick', () => {
    setActivePolygon(polygon1);
    startEditing();
  });

  polygon2.on('dblclick', () => {
    setActivePolygon(polygon2);
    startEditing();
  });

  polygons.value = [polygon1, polygon2];

  if (polygonEditor.value) {
    polygonEditor.value.addAdsorbPolygons([polygon1, polygon2]);
    setActivePolygon(polygon2);
  }
};

const setupEditorEvents = () => {
  if (!polygonEditor.value) return;

  polygonEditor.value.on('add', (event: any) => {
    const newPolygon = event.target as Polygon;
    const extData = newPolygon.getExtData() || {};

    if (!extData.id) {
      extData.id = `polygon-${Date.now()}`;
      extData.name = `多边形-${polygons.value.length + 1}`;
      newPolygon.setExtData(extData);
    }

    polygonEditor.value?.addAdsorbPolygons([newPolygon]);

    newPolygon.on('dblclick', () => {
      setActivePolygon(newPolygon);
      startEditing();
    });

    polygons.value.push(newPolygon);
    setActivePolygon(newPolygon);
    isEditing.value = true;
    emit('polygon-created', newPolygon);
  });

  polygonEditor.value.on('end', (event: any) => {
    const editedPolygon = event.target as Polygon;
    isEditing.value = false;
    emit('polygon-updated', editedPolygon);
  });

  polygonEditor.value.on('adjust', () => {
    isEditing.value = true;
  });
};

const setActivePolygon = (polygon: Polygon | null) => {
  activePolygon.value = polygon;
};

const createPolygon = () => {
  if (!polygonEditor.value) return;

  stopEditing();
  polygonEditor.value.setTarget();
  polygonEditor.value.open();
  isEditing.value = true;
};

const startEditing = () => {
  if (!polygonEditor.value || !activePolygon.value) return;

  polygonEditor.value.setTarget(activePolygon.value);
  polygonEditor.value.open();
  isEditing.value = true;
};

const stopEditing = () => {
  if (!polygonEditor.value) return;

  polygonEditor.value.close();
  isEditing.value = false;
};

const deleteActivePolygon = () => {
  if (!activePolygon.value || !mapInstance.value) return;

  const polygonId = activePolygon.value.getExtData().id;
  mapInstance.value.remove(activePolygon.value);
  polygons.value = polygons.value.filter(poly => poly !== activePolygon.value);
  setActivePolygon(polygons.value[0] || null);
  emit('polygon-deleted', polygonId);
};

// 添加清空所有多边形的方法
const clearAllPolygons = () => {
  if (!mapInstance.value) return;

  // 停止编辑
  stopEditing();

  // 从地图上移除所有多边形
  mapInstance.value.remove(polygons.value);

  // 清空多边形数组
  polygons.value = [];

  // 重置激活的多边形
  setActivePolygon(null);

  // 清除吸附多边形
  if (polygonEditor.value) {
    polygonEditor.value.addAdsorbPolygons([]);
  }
};

const saveCurrentPolygon = () => {
  if (!activePolygon.value) return;

  const extData = activePolygon.value.getExtData();
  const data = {
    id: extData.id,
    name: extData.name,
    path: activePolygon.value.getPath().map(point => [point.lng, point.lat]),
    style: activePolygon.value.getOptions(),
  };
  emit('save-current', data);
};

const saveAllPolygons = () => {
  if (!mapInstance.value || polygons.value.length === 0) return;

  const center = mapInstance.value.getCenter();
  const allData = {
    mapState: {
      center: [center.getLng(), center.getLat()],
      zoom: mapInstance.value.getZoom(),
    },
    polygons: polygons.value.map(poly => {
      const extData = poly.getExtData();
      const options = poly.getOptions();

      return {
        id: extData.id,
        name: extData.name,
        path: poly.getPath().map(point => [point.lng, point.lat]),
        style: {
          strokeColor: options.strokeColor,
          strokeWeight: options.strokeWeight,
          fillColor: options.fillColor,
          fillOpacity: options.fillOpacity,
        },
      };
    }),
  };
  emit('save-all', allData);
};

const loadMapData = (data: {
  mapState: { center: [number, number]; zoom: number };
  polygons: MapPolygon[];
}) => {
  if (!isMapReady.value || !mapInstance.value || !window.AMap) return;

  polygons.value.forEach(poly => mapInstance.value?.remove(poly));
  polygons.value = [];
  setActivePolygon(null);

  mapInstance.value.setCenter(data.mapState.center);
  mapInstance.value.setZoom(data.mapState.zoom);

  addInitialPolygons(window.AMap, data.polygons);
};

// 完善暴露的方法列表，添加clearAllPolygons
defineExpose({
  loadMapData,
  getMapInstance: () => mapInstance.value,
  getActivePolygon: () => activePolygon.value,
  getAllPolygons: () => polygons.value.map(poly => {
    const extData = poly.getExtData();
    const options = poly.getOptions();
    return {
      id: extData.id,
      name: extData.name,
      path: poly.getPath().map(point => [point.lng, point.lat]),
      style: {
        strokeColor: options.strokeColor,
        strokeWeight: options.strokeWeight,
        fillColor: options.fillColor,
        fillOpacity: options.fillOpacity,
      },
    };
  }),
  startEditing,
  stopEditing,
  clearAllPolygons, // 暴露新添加的方法
});

onMounted(() => {
  if (mapContainer.value) initMap();
});

onBeforeUnmount(() => {
  if (polygonEditor.value) polygonEditor.value.close();
  if (mapInstance.value) mapInstance.value.destroy();
  polygons.value = [];
});
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px;
  background-color: #f0f0f0;

  #map-container {
    width: 100%;
    height: 100%;
  }

  .control-panel {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 999;
    background: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-width: 120px;

    button {
      padding: 6px 10px;
      cursor: pointer;
      border: 1px solid #ddd;
      border-radius: 4px;
      background-color: #f9f9f9;
      font-size: 12px;
      transition: all 0.2s;

      &:hover {
        background-color: #e9e9e9;
      }

      &:disabled {
        cursor: not-allowed;
        opacity: 0.6;
      }
    }

    .status-info {
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #eee;
      font-size: 12px;
      color: #666;
    }
  }
}
</style>
